#include<stdio.h>
#include<math.h>

int asc(int x, int y);//升序排序，若x>y,则视为逆序返回1
int desc(int x, int y);//降序排序,若x<y,则视为逆序返回1
int AscAbs(int x, int y);//绝对值升序排序,若fabs(x)>fabs(y)则视为逆序返回1
void Sort(int arr[], int n, int(*f)(int x, int y));

int main()
{
    int (*f[])(int x, int y) = {asc, desc, AscAbs};
    int a[5] = {3, -4, 1, 5, 2};
    int select;
    int n = 5, i;

    //菜单
    while (1)
    {
        printf("1.升序\n");
        printf("2.降序\n");
        printf("3.按绝对值升序\n");
        printf("0.退出\n");
        printf("请做出你的选择\n");
        scanf("%d", &select);

        if (select == 0)
            break;

        if (select < 0 || select > 3)
        {
            printf("请输入正确的选项\n");
            continue;
        }

        printf("排序前: ");
        for (i = 0; i < n; i++)
        {
            printf("%d ", a[i]);
        }
        printf("\n");

        Sort(a, n, f[select - 1]);

        printf("排序后: ");
        for (i = 0; i < n; i++)
        {
            printf("%d ", a[i]);
        }
        printf("\n");
    }
    return 0;
}

int asc(int x, int y)
{
    if (x > y)
        return 1;
    else
        return 0;
}

int desc(int x, int y)
{
    if (x < y)
        return 1;
    else
        return 0;
}

int AscAbs(int x, int y)
{
    if (fabs(x) > fabs(y))
        return 1;
    else
        return 0;
}

void Sort(int arr[], int n, int(*f)(int x, int y))
{
    int i, j, t;

    //冒泡排序
    for (i = 0; i < n - 1; i++)
    {
        for (j = 0; j < n - i - 1; j++)
        {
            if ((*f)(arr[j], arr[j + 1]))//逆序返回1
            {
                t = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = t;
            }
        }
    }
}
